/**
 * 全局用户信息管理模块（Vuex）
 * - 首页加载基础用户数据（头像、昵称、等级/境界/经验、语言、门派、基础货币）
 * - 提供统一的全局数据访问接口与更新通知机制
 * - 内置本地缓存与过期策略，避免重复请求
 */

import api from '@/api'

const CACHE_KEY = 'home_user_info'
const CACHE_TTL_MS = 60 * 1000 // 60秒缓存有效期

const state = {
  // 基础信息
  name: '',
  headUrl: '',
  language: 0,
  // 境界与等级
  levelInfo: {
    real_name: '',
    real_desc: '',
    level: 1,
    exp: 0,
    need_exp: 0
  },
  // 门派信息
  sectInfo: null,
  // 最近一次加载时间戳
  lastLoadedAt: null,
  // 加载状态
  loading: false,
  error: null
}

const getters = {
  nickname: (s) => s.name || '无名侠客',
  avatarUrl: (s) => s.headUrl || '',
  realmName: (s) => s.levelInfo?.real_name || '',
  realmDesc: (s) => s.levelInfo?.real_desc || '',
  level: (s) => s.levelInfo?.level || 1,
  exp: (s) => s.levelInfo?.exp || 0,
  needExp: (s) => s.levelInfo?.need_exp || 0,
  expPercent: (s) => {
    const need = s.levelInfo?.need_exp || 0
    const exp = s.levelInfo?.exp || 0
    if (!need || need <= 0) return 0
    return Math.max(0, Math.min(100, Math.floor((exp / need) * 100)))
  },
  language: (s) => s.language,
  sectInfo: (s) => s.sectInfo || {},
  basicUserInfo: (s) => ({
    name: s.name,
    head_url: s.headUrl,
    level_info: { ...s.levelInfo },
    language: s.language,
    sectInfo: s.sectInfo
  }),
  isLoading: (s) => s.loading,
  lastLoadedAt: (s) => s.lastLoadedAt
}

const mutations = {
  SET_LOADING(state, loading) { state.loading = loading },
  SET_ERROR(state, error) { state.error = error },
  SET_HOME_INFO(state, payload) {
    const d = payload || {}
    state.name = d.name || ''
    state.headUrl = d.head_url || ''
    state.language = typeof d.language === 'number' ? d.language : 0
    state.levelInfo = {
      real_name: d.level_info?.real_name || '',
      real_desc: d.level_info?.real_desc || '',
      level: d.level_info?.level || 1,
      exp: d.level_info?.exp || 0,
      need_exp: d.level_info?.need_exp || 0
    }
    state.sectInfo = d.sectInfo || null
    state.lastLoadedAt = Date.now()
  }
}

function readCache() {
  try {
    const raw = localStorage.getItem(CACHE_KEY)
    if (!raw) return null
    const obj = JSON.parse(raw)
    if (!obj || !obj.timestamp || !obj.data) return null
    if (Date.now() - obj.timestamp > CACHE_TTL_MS) return null
    return obj.data
  } catch (e) { return null }
}

function writeCache(data) {
  try {
    const obj = { timestamp: Date.now(), data }
    localStorage.setItem(CACHE_KEY, JSON.stringify(obj))
  } catch (e) {}
}

function notifyUpdate(data) {
  try {
    const evt = new CustomEvent('userInfoUpdated', { detail: data })
    window.dispatchEvent(evt)
  } catch (e) {}
}

const actions = {
  /**
   * 初始化首页基础用户数据
   * - 优先使用短期缓存，过期则请求接口
   * - 不加载装备属性或角色属性信息
   * - 同步初始化货币到 items 模块（如果返回包含 item 字段）
   */
  async initHomeData({ commit, dispatch, getters }) {
    // 命中缓存则直接使用
    const cached = readCache()
    if (cached) {
      commit('SET_HOME_INFO', cached)
      notifyUpdate(getters.basicUserInfo)
      // 从缓存也回填货币（如果有）
      if (cached.item && typeof cached.item === 'object') {
        dispatch('items/applyCurrenciesFromHomeMap', cached.item, { root: true })
      }
      return cached
    }

    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    try {
      // 兼容已有后端：使用 /role/info 获取首页数据
      const res = await api.request({ url: '/role/info', method: 'POST', data: {} })
      const payload = res && res.data ? res.data : null
      if (!payload) throw new Error('empty_home_info')

      commit('SET_HOME_INFO', payload)
      writeCache(payload)
      notifyUpdate(getters.basicUserInfo)

      // 货币初始化（交给 items 模块）
      if (payload.item && typeof payload.item === 'object') {
        await dispatch('items/applyCurrenciesFromHomeMap', payload.item, { root: true })
      }
      return payload
    } catch (e) {
      commit('SET_ERROR', e?.message || 'load_home_failed')
      return null
    } finally {
      commit('SET_LOADING', false)
    }
  },

  /**
   * 手动刷新（绕过缓存）
   */
  async refreshHomeData({ commit, dispatch, getters }) {
    commit('SET_LOADING', true)
    commit('SET_ERROR', null)
    try {
      const res = await api.request({ url: '/role/info', method: 'POST', data: {} })
      const payload = res && res.data ? res.data : null
      if (!payload) throw new Error('empty_home_info')

      commit('SET_HOME_INFO', payload)
      writeCache(payload)
      notifyUpdate(getters.basicUserInfo)

      if (payload.item && typeof payload.item === 'object') {
        await dispatch('items/applyCurrenciesFromHomeMap', payload.item, { root: true })
      }
      return payload
    } catch (e) {
      commit('SET_ERROR', e?.message || 'refresh_home_failed')
      return null
    } finally {
      commit('SET_LOADING', false)
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}